<template>
    <div :class='$style.form'>
        <a-form ref='formRef' autocomplete='off' :model='formData' :rules='rules' :label-col='{ span: 4 }' :wrapper-col="{ span: 18 }" @finish='submit'>
            <a-form-item label='起始日期' name='date'>
                <a-range-picker valueFormat='YYYY-MM-DD' v-model:value='formData.date' />
            </a-form-item>
            <a-form-item label='回测金额' name='cash'>
                <a-input v-model:value='formData.cash' type='number' />
            </a-form-item>
            <template v-for='(field, index) in props.fields' :key='index'>
                <a-form-item :label='field.name' :name='field.code'>
                    <template v-if='field.type == 1'>
                        <a-input v-model:value='formData[field.code]' />
                    </template>
                    <template v-else-if='field.type == 6'>
                        <XStockSelect :type='field.code_list' v-model:value='formData[field.code]' />
                    </template>
                    <template v-else>
                        <a-select v-model:value='formData[field.code]' :options='field.options'></a-select>
                    </template>
                </a-form-item>
            </template>
            <!-- <a-form-item label='标的' name='code'>
                <a-input v-model:value='formData.code' />
            </a-form-item>
            <a-form-item label='短线' name='sma'>
                <a-input v-model:value='formData.sma' />
            </a-form-item>
            <a-form-item label='长线' name='lma'>
                <a-input v-model:value='formData.lma' />
            </a-form-item>
            <a-form-item label='基准' name='benchmark'>
                <a-select v-model:value='formData.benchmark' :options='BENCHMARK'></a-select>
            </a-form-item> -->
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                <a-button type='primary' html-type='submit' :loading='loading'>运行回测</a-button>
                <a-button style='margin-left: 10px' @click='resetForm'>重置</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script lang='ts' setup>
    import { nextTick, reactive, ref } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { strategyBackTestApi } from '@/api/strategy'
    import { BENCHMARK } from '@/constant'
    import { message } from 'ant-design-vue';


    interface FormDataType {
        date : any;
        cash : any;
        [key:string] : any;
        // code : any;
        // sma : any;
        // lma : any;
        // benchmark : any;
    }

    const props = defineProps<{
        title : string,
        fields? : any[]
    }>()

    const emit = defineEmits<{
        (e : 'finish') : void
    }>()

    const $route = useRoute()
    const $router = useRouter()

    const formData = reactive<FormDataType>({
        date : '',
        cash : '',
        // code : '',
        // sma : '',
        // lma : '',
        // benchmark : '',
    })

    const strategyId = Number($route.params.id)
    const taskId = ref(0)

    const rules = reactive<{
        [key in keyof (typeof formData)]? : any[]
    }>({
        date : [
            {
                required : true,
                message : '请选择起始日期'
            }
        ],

        cash : [
            {
                required : true,
                message : '请输入回测金额'
            }
        ],

        code : [
            {
                required : true,
                message : '请输入标的'
            }
        ],

        // sma : [
        //     {
        //         required : true,
        //         message : '请输入短线'
        //     }
        // ],

        // lma : [
        //     {
        //         required : true,
        //         message : '请输入长线'
        //     }
        // ],

        // benchmark : [
        //     {
        //         required : true,
        //         message : '请选择基准'
        //     }
        // ]
    })

    const formRef = ref()
    const visible = ref(false)
    const loading = ref(false)
    function resetForm(){
      formRef.value.resetFields();
    }

    async function submit(values) {
        let params:any = JSON.parse(JSON.stringify(values))
        if(params.date) {
            params.start_date = params.date[0]
            params.end_date = params.date[1]
            delete params.date
        }

        params.strategy_id = strategyId
        loading.value = true
        const res = await strategyBackTestApi(params)
        loading.value = false
        if(res.success) {
            taskId.value = res.data.task_id
            $router.push('/strategy/backTest/result/' + res.data.task_id)
        }else {
            message.error(res.message)
        }
        
    }

    props.fields.forEach(item => {
        formData[item.code] = ''
        if(item.type == 2) {
            const options = JSON.parse(item.value)
            item.options = Object.keys(options.list).map(key => ({value : key, label : options.list[key]}))
            rules[item.code] = [{required : options.required === 'ture', message : '请选择' + item.name}] 
        }else if(item.type == 6) {
            const option = JSON.parse(item.value)
            item.code_list = option.code_list
            rules[item.code] = [{required : option.required === 'ture', message : '请选择' + item.name}] 
        } else {
            if(item.value) {
                try {
                    const option = JSON.parse(item.value)
                    if(option) {
                        let rule:any = {
                            required : option.required === 'ture',
                            validator : (_rule, value) => {
                                if(value === '') {
                                    if(option.required) {
                                        
                                        return Promise.reject('请填写' + item.name);
                                    }else {
                                        return Promise.resolve()
                                    }
                                    
                                }

                                if(option.number) {
                                    value = Number(value)
                                    if(isNaN(value)) {
                                        return Promise.reject('请输入数字');
                                    }
                                    if('min' in option.number && value < option.number.min) {
                                        return Promise.reject(item.name + `不能小于${option.number.min}`);
                                    }

                                    if('max' in option.number && value > option.number.max) {
                                        return Promise.reject(item.name + `不能大于${option.number.max}`);
                                    }
                                }

                                return Promise.resolve()
                            }
                        }

                        rules[item.code] = [rule]

                    }

                } catch (error) {
                    
                }
            }
        }

        
    })

</script>

<style lang='scss' module>
    .form{
        width: 600px;
    }
</style>